<template>
    <div class="title">
        商品分类
        <el-button
            type="primary"
            style="float: right; 
            margin-right: 10px; margin-top:10px; 
            background-color: #fff; color: #000; border:1px solid #e5e5e5"
            @click="showAddCateDialog = true"
        >
            添加分类
        </el-button>
    </div>
    <el-table
        :data="tableData"
        :border="parentBorder"
        :preserve-expanded-content="preserveExpanded"
        style="width: 100%"
    >
        <el-table-column label="序号" prop="id" />
        <el-table-column label="分类名">
            <template #default="scope">
                <el-input
                    v-if="scope.row.isEditing"
                    v-model="scope.row.cateName"
                    size="small"
                />
                <span v-else>{{ scope.row.cateName }}</span>
            </template>
        </el-table-column>
        <el-table-column label="是否启用">
            <template #default="scope">
                <el-switch
                    v-model="scope.row.state"
                    size="small"
                    :disabled="!scope.row.isEditing"
                />
            </template>
        </el-table-column>
        <el-table-column label="操作">
            <template #default="scope">
                <el-button
                    v-if="scope.row.isEditing"
                    size="small"
                    type="success"
                    @click="saveEdit(scope.row)"
                >
                    完成
                </el-button>
                <el-button
                    v-else
                    size="small"
                    type="primary"
                    @click="startEdit(scope.row)"
                >
                    编辑
                </el-button>
                <el-button
                    size="small"
                    type="danger"
                    :style="{ backgroundColor: '#f56c6c' }"
                    @click="handleDelete(scope.row.id)"
                >
                    删除
                </el-button>
            </template>
        </el-table-column>
    </el-table>
    <div class="demo-pagination-block">
        <el-pagination
            v-model:current-page="currentPage"
            v-model:page-size="pageSize"
            :page-sizes="[5, 10, 15, 20]"
            layout="total, sizes, prev, pager, next, jumper"
            :total="total"
            @size-change="handleSizeChange"
            @current-change="handleCurrentChange"
        />
    </div>
    <!-- 添加分类的对话框 -->
    <el-dialog
        v-model="showAddCateDialog"
        title="添加商品分类"
        :close-on-click-modal="false"
    >
        <el-form
            ref="addCateFormRef"
            :model="addCateForm"
            label-width="80px"
        >
            <el-form-item label="分类名称">
                <el-input v-model="addCateForm.cateName" />
            </el-form-item>
            <el-form-item label="是否启用">
                <el-switch v-model="addCateForm.state" />
            </el-form-item>
        </el-form>
        <template #footer>
            <span class="dialog-footer">
                <el-button @click="showAddCateDialog = false">取消</el-button>
                <el-button type="primary" @click="handleAddCate">确定</el-button>
            </span>
        </template>
    </el-dialog>
</template>

<script lang="ts" setup>
import { ref, onMounted } from 'vue';
import { getcatelist, editcate, delcate, addcate } from '../../api/account';
import { ElMessageBox, ElMessage } from 'element-plus';

// 初始化分页相关变量
const currentPage = ref(1);
const pageSize = ref(5);
const total = ref(0);
const tableData = ref([]);

// 添加分类相关变量
const showAddCateDialog = ref(false);
const addCateForm = ref({
    cateName: '',
    state: false
});
const addCateFormRef = ref(null);

const fetchCatelist = async () => {
    try {
        const response = await getcatelist({ currentPage: currentPage.value, pageSize: pageSize.value });
        total.value = response.total;
        tableData.value = response.data.map(item => ({
           ...item,
            isEditing: false,
            originalState: item.state,
            originalCateName: item.cateName,
            state: item.state === 1
        }));
        localStorage.setItem('categoryData', JSON.stringify(tableData.value));
    } catch (error) {
        console.error('获取商品分类列表失败', error);
    }
};

onMounted(() => {
    fetchCatelist();
    const storedData = localStorage.getItem('categoryData');
    if (storedData) {
        tableData.value = JSON.parse(storedData).map(item => ({
           ...item,
            isEditing: false,
            originalState: item.state,
            originalCateName: item.cateName,
            state: item.state === 1
        }));
    }
});

const handleSizeChange = (newPageSize) => {
    pageSize.value = newPageSize;
    fetchCatelist();
};

const handleCurrentChange = (newCurrentPage) => {
    currentPage.value = newCurrentPage;
    fetchCatelist();
};

const startEdit = (row) => {
    row.isEditing = true;
    row.originalState = row.state;
    row.originalCateName = row.cateName;
};

const saveEdit = async (row) => {
    try {
        const { id, cateName, state } = row;
        const editData = {
    id,
    cateName,
    state: state? 1 : 0
};
const response = await editcate(editData);
        if (response.code === 0) {
            row.isEditing = false;
            row.originalState = state;
            row.originalCateName = cateName;
            ElMessage.success('修改商品分类成功');
            const updatedData = tableData.value.map(item => item.id === row.id? row : item);
            localStorage.setItem('categoryData', JSON.stringify(updatedData));
        } else {
            row.state = row.originalState;
            row.cateName = row.originalCateName;
            row.isEditing = false;
            ElMessage.error('修改失败，参数错误');
        }
    } catch (error) {
        row.state = row.originalState;
        row.cateName = row.originalCateName;
        row.isEditing = false;
        console.error('修改商品分类时出错', error);
        ElMessage.error('修改失败，请检查网络或联系管理员');
    }
};

const handleDelete = async (id) => {
    const confirm = await ElMessageBox.confirm(
        '确定要删除该分类吗？',
        '提示',
        {
            confirmButtonText: '确定',
            cancelButtonText: '取消',
            type: 'warning'
        }
    );
    if (confirm === 'confirm') {
        try {
            const response = await delcate(id);
            if (response.code === 0) {
                tableData.value = tableData.value.filter(item => item.id!== id);
                ElMessage.success('删除商品分类成功');
                localStorage.setItem('categoryData', JSON.stringify(tableData.value));
                fetchCatelist();
            } else {
                ElMessage.error('删除失败，参数错误');
            }
        } catch (error) {
            console.error('删除商品分类时出错', error);
            ElMessage.error('删除失败，请检查网络或联系管理员');
        }
    }
};

const handleAddCate = async () => {
    try {
        const response = await addcate({
            cateName: addCateForm.value.cateName,
            state: addCateForm.value.state
        });
        if (response.code === 0) {
            ElMessage.success('添加商品分类成功');
            showAddCateDialog.value = false;
            addCateForm.value.cateName = '';
            addCateForm.value.state = false;
            fetchCatelist();
        } else {
            ElMessage.error('添加失败，参数错误');
        }
    } catch (error) {
        console.error('添加商品分类时出错', error);
        ElMessage.error('添加失败，请检查网络或联系管理员');
    }
};
</script>

<style scoped>
.title {
    width: 100%;
    height: 50px;
    font-size: 20px;
    color: #333;
    line-height: 50px;
    padding-left: 20px;
    text-align: left;
    border-bottom: 1px solid #dcdfe6;
}

</style>